package com.jeecms.wicool.action.user;

import static com.jeecms.common.page.SimplePage.cpn;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.wicool.entity.user.UserCoupon;
import com.jeecms.wicool.entity.util.Dictionary2;
import com.jeecms.wicool.manager.user.UserCouponMng;
import com.jeecms.wicool.manager.util.DictionaryMng;

@Controller
public class UserCouponAct {
	private static final Logger log = LoggerFactory.getLogger(UserCouponAct.class);

	@RequestMapping("/user/v_listUserCoupon.do")
	public String list(Integer userId,Integer couponType,String mobile,String couponName,Integer couponSource,Short status,
			Integer pageNo, HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPage( userId, couponType, mobile,couponName, couponSource, status,
				cpn(pageNo), CookieUtils.getPageSize(request),CmsUtils.getUser(request));
		List<UserCoupon> list = (List<UserCoupon>) pagination.getList();
		
		List<Dictionary2> listCouponType=DicMng.getList("coupon_type");
		List<Dictionary2> listUserCouponStatus=DicMng.getList("userCoupon_status");
		List<Dictionary2> listCouponSource=DicMng.getList("coupon_source");
		Map<String,String> map = new HashMap<String,String>();
		Map<String,String> map2 = new HashMap<String,String>();
		Map<String,String> map3 = new HashMap<String,String>();
		 for(Dictionary2 d : listCouponType){
			 map.put(d.getDicCode().toString(), d.getDicName());
		 }for(Dictionary2 d : listUserCouponStatus){
			 map2.put(d.getDicCode().toString(), d.getDicName());
		 }for(Dictionary2 d : listCouponSource){
			 map3.put(d.getDicCode().toString(), d.getDicName());
		 }
		 for(UserCoupon p : list){
			 if(map.containsKey(p.getCouponType().toString())){
				 p.setCouponTypeName(map.get(p.getCouponType().toString()));
			 } if(map2.containsKey(p.getStatus().toString())){
				 p.setStatusName(map2.get(p.getStatus().toString()));
			 }if(map3.containsKey(p.getCouponSource().toString())){
				 p.setCouponSourceName(map3.get(p.getCouponSource().toString()));
			 }
		 }	
		model.addAttribute("pagination", pagination);
		model.addAttribute("couponType", couponType);
		model.addAttribute("couponName", couponName);
		model.addAttribute("status", status);
		model.addAttribute("userId", userId);
		model.addAttribute("couponSource", couponSource);
		model.addAttribute("listCouponType", listCouponType);
		model.addAttribute("listUserCouponStatus", listUserCouponStatus);
		return "user/list_UserCoupon";
	}

	

	@RequestMapping("/user/v_addUserCoupon.do")
	public String add(ModelMap model,HttpServletRequest request) {
		UserCoupon userCoupon= new UserCoupon();
		List<Dictionary2> listCouponType=DicMng.getList("coupon_type");
		List<Dictionary2> listUserCouponStatus=DicMng.getList("userCoupon_status");
		List<Dictionary2> listCouponSource=DicMng.getList("coupon_source");
	
		model.addAttribute("listCouponType", listCouponType);
		model.addAttribute("listUserCouponStatus", listUserCouponStatus);
		model.addAttribute("listCouponSource", listCouponSource);
		
		model.addAttribute("userCoupon", userCoupon);
		return "user/add_UserCoupon";
	}

	@RequestMapping("/user/v_editUserCoupon.do")
	public String edit(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UserCoupon userCoupon = manager.findById(id);
		List<Dictionary2> listCouponType=DicMng.getList("coupon_type");
		List<Dictionary2> listUserCouponStatus=DicMng.getList("userCoupon_status");
		List<Dictionary2> listCouponSource=DicMng.getList("coupon_source");
	
		model.addAttribute("listCouponType", listCouponType);
		model.addAttribute("listUserCouponStatus", listUserCouponStatus);
		model.addAttribute("listCouponSource", listCouponSource);
		
		model.addAttribute("userCoupon", userCoupon);
		return "user/edit_UserCoupon";
	}

	@RequestMapping("/user/v_viewUserCoupon.do")
	public String view(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UserCoupon userCoupon = manager.findById(id);
		
		
		userCoupon.setCouponTypeName(DicMng.findByDicCode("coupon_type", Short.parseShort(String.valueOf(userCoupon.getCouponType()))).getDicName());
		userCoupon.setStatusName(DicMng.findByDicCode("userCoupon_status", Short.parseShort(String.valueOf(userCoupon.getStatus()))).getDicName());
		userCoupon.setCouponSourceName(DicMng.findByDicCode("coupon_source", Short.parseShort(String.valueOf(userCoupon.getCouponSource()))).getDicName());
		model.addAttribute("userCoupon", userCoupon);
		return "user/view_UserCoupon";
	}

	@RequestMapping("/user/o_saveUserCoupon.do")
	public String save(UserCoupon bean,Integer userId,Integer couponId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		bean.setStatus(Short.parseShort("1"));
		bean = manager.save(bean, userId,couponId);
		log.info("save UserCoupon id={}", bean.getId());
		cmsLogMng.operating(request, "UserCoupon.log.save", "id=" + bean.getId());
		return "redirect:v_listUserCoupon.do";
	}

	@RequestMapping("/user/o_updateUserCoupon.do")
	public String update(UserCoupon bean, Integer userId,Integer couponId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		bean = manager.update(bean, userId,couponId);
		model.addAttribute("message", "global.success");
		log.info("update UserCoupon success. id={}", bean.getId());
		cmsLogMng.operating(request, "UserCoupon.log.update", "id=" + bean.getId());
		return "redirect:v_listUserCoupon.do";
	}
	@RequestMapping("/user/o_isUsed.do")
	public String isUsed( Integer id, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateUpdate(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UserCoupon bean = manager.findById(id);
		bean.setStatus(Short.parseShort("2"));
		SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateTime = simpleTime.format(new Date());
		Timestamp t = Timestamp.valueOf(dateTime);
		bean.setUsedTime(t);
		model.addAttribute("message", "global.success");
		log.info("update UserCoupon success. id={}", bean.getId());
		cmsLogMng.operating(request, "UserCoupon.log.update", "id=" + bean.getId());
		return list(bean.getUser().getId(), null, null,null, null, null, pageNo, request, model);
	}

	@RequestMapping("/user/o_deleteUserCoupon.do")
	public String delete(Integer[] ids, Integer userId,Integer couponType,String couponName,Integer couponSource,Short status, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UserCoupon[] beans = manager.deleteByIds(ids);
		for (UserCoupon bean : beans) {
			log.info("delete UserCoupon id={}", bean.getId());
			cmsLogMng.operating(request, "UserCoupon.log.delete", "id="
					+ bean.getId() );
		}
		return list(userId, couponType,null,couponName,couponSource,status, pageNo, request, model);
	}

	private WebErrors validateSave(UserCoupon bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		return errors;
	}

	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		// TODO 验证是否为管理员，管理员不允许修改。
		return errors;
	}

	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Integer id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		UserCoupon entity = manager.findById(id);
		if (errors.ifNotExist(entity, UserCoupon.class, id)) {
			return true;
		}
		return false;
	}

	@Autowired
	private UserCouponMng manager;
	@Autowired
	private CmsLogMng cmsLogMng;
	@Autowired
	private DictionaryMng DicMng;
}
